package com.cartoon.activity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.SPStaticUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.cartoon.R;

import com.cartoon.adapter.LRYCarttonReadingContentAdapter;
import com.cartoon.databinding.CarttonReadingActivityBinding;
import com.cartoon.databinding.KkCarttonReadingActivityBinding;
import com.cartoon.databinding.LryCarttonReadingActivityBinding;
import com.cartoon.databinding.LrySearchCarttonItemBinding;
import com.cartoon.model.CartoonDataViewModel;

import java.util.List;
import java.util.concurrent.TimeUnit;

import base.QActivity;
import cartoon.room.read.room.CartoonReadHistoryModel;
import cartoon.room.read.room.CartoonReadHistoryViewModel;
import constant.AppConstants;
import http.Api;
import io.reactivex.Flowable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import model.CarttonKKContentModel;
import model.CarttonKKDirectoryModel;
import model.CarttonLRYContentModel;
import model.CarttonLRYDirectoryModel;
import model.CarttonLRYHistrory;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class LRYCarttonReadingActivity extends QActivity {

    private List<CarttonLRYDirectoryModel.DataBean.ChapterListBean> lryListData;

    private RecyclerView.OnScrollListener loadingMoreListener;
    private int timeOut;
    private boolean next = true;
    private Disposable disposable;
    private LryCarttonReadingActivityBinding binding;
    private String lryCartoonId;
    private LRYCarttonReadingContentAdapter lryCarttonReadingContentAdapter;
    private CartoonReadHistoryViewModel viewModel;
    private List<CarttonLRYHistrory> lryHistrory;
    private String lryname;
    private String lrypic;
    private String lrytitle;

    @Override
    public int getLayoutRes() {
        return R.layout.lry_cartton_reading_activity;
    }

    @Override
    public void initView() {
        binding = DataBindingUtil.setContentView(this, getLayoutRes());
        Bundle bundle = getIntent().getExtras();
        lryCartoonId = bundle.getString("lrychapterId");
        lryname = bundle.getString("lryname");
        lrypic = bundle.getString("lrypic");
        lrytitle = bundle.getString("lrytitle");

    }

    @Override
    public void initData() {
        viewModel = new ViewModelProvider(this).get(CartoonReadHistoryViewModel.class);



//        binding.rvKkreading.scrollToPosition(0);
    }

    @Override
    public void initListener() {
        CartoonDataViewModel.getInstance().getLRYData().observe(this, new Observer<List<CarttonLRYDirectoryModel.DataBean.ChapterListBean>>() {
            @Override
            public void onChanged(List<CarttonLRYDirectoryModel.DataBean.ChapterListBean> chapterListBeans) {

                lryListData = chapterListBeans;
            }
        });


        CartoonDataViewModel.getInstance().getLRYHistroryData().observe(this, new Observer<List<CarttonLRYHistrory>>() {
            @Override
            public void onChanged(List<CarttonLRYHistrory> carttonLRYHistrories) {
                lryHistrory = carttonLRYHistrories;
            }
        });
        binding.ivBlack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });


//        loadingMoreListener = new RecyclerView.OnScrollListener() {
//            //到达顶部和底部监听
//            @Override
//            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
//                super.onScrollStateChanged(recyclerView, newState);
//                // OnScrollListener.SCROLL_STATE_FLING; //屏幕处于甩动状态
//                // OnScrollListener.SCROLL_STATE_IDLE; //停止滑动状态
//                // OnScrollListener.SCROLL_STATE_TOUCH_SCROLL;// 手指接触状态
//                // 记录当前滑动状态
//
//
//
//
//                if (newState == RecyclerView.SCROLL_STATE_IDLE) { //当前状态为停止滑动
//                    if (!binding.rvLryreading.canScrollVertically(1)) { // 到达底部
//                        Toast toast=Toast.makeText(LRYCarttonReadingActivity.this, "请稍后再下拉刷新", Toast.LENGTH_SHORT);
//                        toast.show();
//                     //   ToastUtils.showLong("请稍后再下拉刷新");
//
//                        for (int i = 0; i < lryListData.size(); i++) {
//                            if (lryListData.get(i).getChapterId().equals(lryCartoonId)) {
//                                if (i + 1 < lryListData.size()) {
//                                    if (timeOut == 1) {
//                                        timeOut = 5;
//                                        next = true;
//
//                                        getLRYCartoonContent(lryListData.get(i + 1).getChapterId());
//                                        lryCartoonId = lryListData.get(i + 1).getChapterId();
//                                        return;
//                                    }
//                                }
//
//                            }
//                        }
//                    } else if (!binding.rvLryreading.canScrollVertically(-1)) { // 到达顶部
//                        for (int i = 0; i < lryListData.size(); i++) {
//                            if (lryListData.get(i).getChapterId().equals(lryCartoonId)) {
//                                if (i - 1 >= 0) {
//                                    if (timeOut == 1) {
//                                        timeOut = 5;
//
//                                        next = false;
//
//                                        getLRYCartoonContent(lryListData.get(i - 1).getChapterId());
//                                        lryCartoonId = lryListData.get(i - 1).getChapterId();
//                                        return;
//                                    }
//
//                                }
//
//                            }
//                        }
//                       Toast toast=Toast.makeText(LRYCarttonReadingActivity.this, "请稍后再上拉刷新", Toast.LENGTH_SHORT);
//                        toast.show();
//
//                     //   ToastUtils.showLong("请稍后再上拉刷新");
//                    }
//                }
//            }
//
//
//
//            //上滑下滑监听
//            @Override
//            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
//                super.onScrolled(recyclerView, dx, dy);
//                if (dy < 0) { // 当前处于上滑状态
//
//                } else if (dy > 0) { // 当前处于下滑状态
//
//                }
//            }
//        };
//
//        binding.rvLryreading.addOnScrollListener(loadingMoreListener);

    }

    @Override
    public void networkMessage() {
        getLRYCartoonContent(lryCartoonId);
    }

    public void getLRYCartoonContent(String id) {

//        id ="560796c6-83d9-3903-86ad-df955ae3ab6e";
        Call<CarttonLRYContentModel> call = Api.getInstance().service.getLRYCartoonContent(id);
        call.enqueue(new Callback<CarttonLRYContentModel>() {
            @Override
            public void onResponse(Call<CarttonLRYContentModel> call, Response<CarttonLRYContentModel> response) {
                LogUtils.d("网络请求数据" + call.toString(), response.body());

                if (response.body() != null && response.body().getData() != null) {
                    lryCarttonReadingContentAdapter = null;
                    GridLayoutManager lryManager = new GridLayoutManager(LRYCarttonReadingActivity.this, 1, GridLayoutManager.VERTICAL, false);

                    binding.rvLryreading.setLayoutManager(lryManager);//
                    lryCarttonReadingContentAdapter = new LRYCarttonReadingContentAdapter(R.layout.lry_cartton_reading_content_item, response.body().getData());
                    binding.rvLryreading.setAdapter(lryCarttonReadingContentAdapter);

                    setTime();

                    timeOut = 2;
//                    CarttonKKContentModel.DataBean data = response.body().getData();
                    List<String> data = response.body().getData();
//                    binding.rvLryreading.scrollToPosition(0);
//                    lryCarttonReadingContentAdapter.replaceData(data);


                    int animePlayHistory = SPStaticUtils.getInt("lryCarttonHistory", 0);
                    int newId = animePlayHistory + 1;
                    LogUtils.d("保存的Id" + newId);
                    SPStaticUtils.put("lryCarttonHistory", newId);
//

//                    LogUtils.d("看覅让客服A"+GsonUtils.toJson(lryListData));
//                    LogUtils.d("看覅让客服B"+GsonUtils.toJson(lryHistrory));


//                    binding.rvKkreading.scrollToPosition(0);

                    if (lryListData != null && lryListData.size() >= 1) {
//                        GsonUtils.toJson(lryListData);
                        for (int i = 0; i < lryListData.size(); i++) {
                            if (lryListData.get(i).getChapterId().equals(lryCartoonId)) {
                                viewModel.addHistoryDao(new CartoonReadHistoryModel(newId, 1, lryCartoonId, lryname, lryListData.get(i).getTitle(), lrypic));
                            }
                        }
                        viewModel.getAllSLive().getValue();
                    } else {
//                        GsonUtils.toJson(lryHistrory);
                        viewModel.addHistoryDao(new CartoonReadHistoryModel(newId, 1, lryCartoonId, lryname, lrytitle, lrypic));
                        viewModel.getAllSLive().getValue();
                    }

//                    binding.tvTitle.setText(data.getComic_info().getTitle());
//                    if (next) {
//                        LogUtils.d("开发开发看W");
//                        //下一话的时候就重0位置开始看
//                        binding.rvReading.scrollToPosition(0);
//
//                    } else {
//                        LogUtils.d("开发开发看Q" + data.getComic_info().getImages().size());
//                        //上一话的时候就重最后的位置开始看
//                        binding.rvReading.scrollToPosition(data.getComic_info().getImages().size() - 2);
//
//                    }


//                    carttonReadingContentAdapter.replaceData(data.getComic_info().getImages());


                } else {
                    if (response.body() != null && response.body().getMsg() != null) {
                        ToastUtils.showLong(response.body().getMsg() + "状态码:" + response.code());
                    }
                }


            }

            @Override
            public void onFailure(Call<CarttonLRYContentModel> call, Throwable t) {
                LogUtils.d("请切换模式试下  网络请求失败:" + t.getMessage());
                ToastUtils.showLong("请切换模式  网络请求失败:" + t.getMessage());

            }
        });
    }


    public void setTime() {
        stopDisposable(disposable);
        disposable = Flowable.timer(1 * 5000, TimeUnit.MILLISECONDS)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Long>() {
                    @Override
                    public void accept(Long aLong) throws Exception {

                        timeOut = 1;

                    }
                });
    }


    /**
     * 关闭定时器
     *
     * @param disposable 定时器
     */
    private void stopDisposable(Disposable disposable) {
        if (disposable != null && !disposable.isDisposed()) {
            disposable.dispose();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        loadingMoreListener = null;
        stopDisposable(disposable);
    }
}
